package br.com.extrajudicial.controllers;

import org.springframework.beans.factory.annotation.Autowired;

import br.com.caelum.vraptor.Delete;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.extrajudicial.dao.AddressDao;
import br.com.extrajudicial.dao.ItemDao;
import br.com.extrajudicial.dao.OrderDao;
import br.com.extrajudicial.interceptors.RequireUser;
import br.com.extrajudicial.models.Cart;
import br.com.extrajudicial.models.Item;
import br.com.extrajudicial.models.ItemOrder;
import br.com.extrajudicial.models.Order;

@Resource
public class CartController {
	
	@Autowired private Result result;
	@Autowired private ItemDao itemDao;
	@Autowired private AddressDao addressDao;
	@Autowired private OrderDao orderDao;
	@Autowired private Cart cart;
	
	@Get @Path("/cart/add")
	@RequireUser
	public void add(Long itemId) {
		Item item = itemDao.load(itemId);
		this.result.include("item", item);
	}
	
	@Post @Path("/cart")
	@RequireUser
	public void save(ItemOrder cartItem) {
		this.itemDao.refresh(cartItem.getItem());
		this.cart.add(cartItem);
		this.result.redirectTo(ItemsController.class).items();
	}

	@Get @Path("/cart")
	@RequireUser
	public void cart() { 
		this.result.include("addresses", this.addressDao.listCurrentUserAddresses());
	}
	
	@Delete @Path("/cart/{index}")
	@RequireUser
	public void remove(int index) {
		this.cart.remove(index);
		this.result.redirectTo(CartController.class).cart();
	}
	
	@Post @Path("/cart/finishOrder")
	@RequireUser
	public void finishOrder(Order order) {
		this.orderDao.save(order);
		this.result.redirectTo(OrdersController.class).view(order.getId());		
	}
	
}
